package com.sj.uabrowser.app;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.text.TextPaint;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;

import static android.content.Context.WIFI_SERVICE;

public class PhoneUtil {
    public static Bitmap photo;

    public static Bitmap addWaterMark(Activity act,Bitmap src,String info,int alpha) {
        String[] lines=info.split("\n");

        int w = src.getWidth();
        int h = src.getHeight();

        TextPaint paint=new TextPaint();
        paint.setAlpha(alpha);
        paint.setColor(Color.DKGRAY);
        paint.setAntiAlias(true);
        int textSize = Util.transPX(20.0F);
        paint.setTextSize(textSize);
        paint.setTextSkewX(-0.25f);
        paint.setFakeBoldText(true);
        Bitmap newb = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas cv = new Canvas(newb);
        cv.drawBitmap(src, 0, 0, paint);
        for (int i = 0; i < lines.length; i++) {
            cv.drawText(lines[i], 100, h-textSize*(lines.length-1.2f*i)-5, paint);
        }
        cv.save();
        cv.restore();
        return newb;
    }

    public static Bitmap analyzeGalleryPhotoResult_NoRecycle(Context context, Intent data) {
        if (data == null)
            return null;
        Log.i("CameraUtil:", data.getData().toString());
        Uri uri = data.getData();
        if (uri != null) {
            Log.e("XXX", "uri不为null");
            if (uri.getPath().startsWith("file:")) {
                Log.e("XXX", "file:" + uri.getPath());
                photo = getBitmapFromMedia(context, new File(uri.getPath()));
            } else {
                try {
                    Log.e("XXX", "无file:" + uri.getPath());
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    // 获取这个图片的宽和高
                    Bitmap bitmap = BitmapFactory.decodeStream(context
                                    .getContentResolver().openInputStream(uri), null,
                            options); // 此时返回bm为空
                    options.inJustDecodeBounds = false;
                    // 计算缩放比,超过800W进行压缩

                    options.inSampleSize = (options.outHeight
                            * options.outWidth > 800 * 10000) ? 2 : 1;
                    // 重新读入图片，注意这次要把options.inJustDecodeBounds 设为 false哦
                    photo = BitmapFactory.decodeStream(context
                                    .getContentResolver().openInputStream(uri), null,
                            options);
                    Log.e("XXX", "simple size:" + options.inSampleSize
                            + " " + options.outHeight + "X" + options.outWidth);
                    // Cursor c= context.getContentResolver().query(uri, null,
                    // null, null, null);
                    // c.moveToFirst();
                    // String filepath=c.getString(c.getColumnIndex("_data"));
                    // Log.i("CameraUtil", "content real path:"+filepath);
                    // photo=BitmapFactory.decodeFile(filepath);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }

        if (photo == null) {
            Log.e("XXX", "photo==null");
            photo = data.getParcelableExtra("data");
        }
        return photo;

    }


    public static Bitmap analyzeGalleryPhotoResult(Context context, Intent data) {
        if (data == null)
            return null;
        Log.i("CameraUtil:", data.getData().toString());
        recycleTempPhoto();
        Uri uri = data.getData();
        if (uri != null) {
            Log.e("XXX", "uri不为null");
            if (uri.getPath().startsWith("file:")) {
                Log.e("XXX", "file:" + uri.getPath());
                photo = getBitmapFromMedia(context, new File(uri.getPath()));
            } else {
                try {
                    Log.e("XXX", "无file:" + uri.getPath());
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    // 获取这个图片的宽和高
                    Bitmap bitmap = BitmapFactory.decodeStream(context
                                    .getContentResolver().openInputStream(uri), null,
                            options); // 此时返回bm为空
                    options.inJustDecodeBounds = false;
                    // 计算缩放比,超过800W进行压缩

                    options.inSampleSize = (options.outHeight
                            * options.outWidth > 800 * 10000) ? 2 : 1;
                    // 重新读入图片，注意这次要把options.inJustDecodeBounds 设为 false哦
                    photo = BitmapFactory.decodeStream(context
                                    .getContentResolver().openInputStream(uri), null,
                            options);
                    Log.e("XXX", "simple size:" + options.inSampleSize
                            + " " + options.outHeight + "X" + options.outWidth);
                    // Cursor c= context.getContentResolver().query(uri, null,
                    // null, null, null);
                    // c.moveToFirst();
                    // String filepath=c.getString(c.getColumnIndex("_data"));
                    // Log.i("CameraUtil", "content real path:"+filepath);
                    // photo=BitmapFactory.decodeFile(filepath);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }

        if (photo == null) {
            Log.e("XXX", "photo==null");
            photo = data.getParcelableExtra("data");
        }
        return photo;

    }

    public static String analyzeScanResult(Intent data) {
        if (data != null) {
            return data.getStringExtra("Result");
        } else {
            return "";
        }
    }

    public static Bitmap getBitmapFromMediaNoRecycle(Context context, File file) {
        recycleTempPhoto();
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            // 获取这个图片的宽和高
            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(),
                    options); // 此时返回bm为空
            options.inJustDecodeBounds = false;
            // 计算缩放比,超过800W进行压缩

            options.inSampleSize = (options.outHeight * options.outWidth > 800 * 10000) ? 2
                    : 1;
            // 重新读入图片，注意这次要把options.inJustDecodeBounds 设为 false哦
            System.out.println("simple size:" + options.inSampleSize + " "
                    + options.outHeight + "X" + options.outWidth);

            // 强制异常处理,如果内存溢出则压缩

            photo = BitmapFactory.decodeFile(file.getAbsolutePath(), options);

            // return
            // Media.getBitmap(context.getContentResolver(),Uri.fromFile(file));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return photo;
    }

    public static Bitmap getBitmapFromMedia(Context context, File file) {
        recycleTempPhoto();
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            // 获取这个图片的宽和高
            BitmapFactory.decodeFile(file.getAbsolutePath(),options); // 此时返回bm为空

            // 计算缩放比,超过800W进行压缩

            options.inSampleSize = (options.outHeight * options.outWidth > 800 * 10000) ? 2
                    : 1;
            // 重新读入图片，注意这次要把options.inJustDecodeBounds 设为 false哦
            System.out.println("simple size:" + options.inSampleSize + " "
                    + options.outHeight + "X" + options.outWidth);

            // 强制异常处理,如果内存溢出则压缩
            options.inJustDecodeBounds = false;
            photo = BitmapFactory.decodeFile(file.getAbsolutePath(), options);

            // return
            // Media.getBitmap(context.getContentResolver(),Uri.fromFile(file));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return photo;
    }



    public static Bitmap analyzeCaptureResult(Intent data) {
        if (data == null)
            return null;
        recycleTempPhoto();
        Uri uri = data.getData();
        if (uri != null) {
            photo = BitmapFactory.decodeFile(uri.getPath());
        }

        if (photo == null) {
            Bundle bd = data.getExtras();
            if (bd != null) {
                photo = (Bitmap) bd.get("data");
            }
        }
        if (photo == null) {
            Util.showToastShort("获取照片失败");
        }
        return photo;
    }

    public static void recycleBitmap(Bitmap img) {
        if (img != null && !img.isRecycled()) {
            img.recycle();
            img = null;
        }
    }

    public static void recycleTempPhoto() {
        if (photo != null && !photo.isRecycled()) {
            photo.recycle();
            photo = null;
        }
    }

    public static boolean checkExternalStorage() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            Util.showToastLong("SD存储设备未准备好");
            return false;
        }
    }

    public static File saveBitmap(Bitmap bitmap, File file) {
//        if (file.exists()) {
//            file.delete();
//        }
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            if (bitmap.compress(CompressFormat.JPEG, 100, out)) {
                out.flush();
                out.close();
            }
            return file;
        } catch (Exception e) {
            e.printStackTrace();
            return null;

        }
    }

    public static File saveBitmap(Bitmap bitmap, String filename) {
        return saveBitmap(bitmap, new File(filename));
    }

    public static void callPhone(Activity context, String phone) {
        String encodedHash = Uri.encode("#");
        phone = phone.replaceAll("#", encodedHash);
        Uri uri = Uri.parse("tel:" + phone);
        String action = Intent.ACTION_CALL;

        Intent it = new Intent(action, uri);
        context.startActivityForResult(it, 99);
    }

    public static void dialPhone(Context context, String phone) {
        String encodedHash = Uri.encode("#");
        phone = phone.replaceAll("#", encodedHash);
        Uri uri = Uri.parse("tel:" + phone);
        Intent it = new Intent(Intent.ACTION_DIAL, uri);
        context.startActivity(it);
    }

    public static boolean isWifi(Context mContext) {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        }
        return false;
    }

    public static void openWifiConfigAct(Activity mContext) {
        Intent i = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
        mContext.startActivityForResult(i, 0);
    }

    public static boolean isNetworkAvailable(Context mContext) {
        ConnectivityManager
                manager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (manager.getActiveNetworkInfo() != null) {
            return manager.getActiveNetworkInfo().isAvailable();
        }
        return false;
    }

    public static String getWifiName(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        return wifiInfo.getSSID();
    }
}
